<template>
  <div class="pic-wrap" >
    <a-upload
      :customRequest="httpRequest"
      list-type="picture-card"
      :file-list="fileList"
      :beforeUpload="beforeUpload"
      @change="uploadImg"
      @preview="handlePreview"
      :disabled="disabled"
    >
      <div v-if="fileList.length < limit">
        <div v-if="!loading">
          <a-icon type="plus" />
          <div class="ant-upload-text">
            上传
          </div>
        </div>
        <div v-else style="position: relative">
          <a-icon class="change-img" v-if="loading" type="loading" />
        </div>
      </div>
    </a-upload>
    <!--<a-modal :visible="previewVisible" :width="1024" :footer="null" @cancel="handleCancel" style="z-index: 1004" class="img-modal">
      <img alt="example" style="width: 100%;" :src="previewImage" />
    </a-modal>
    -->
        <viewer
          :images="images"
          @inited="inited"
          class="viewer"
          ref="viewer"
        >
         <img v-show="false" v-for="src in images" :src="src" :key="src" />
        </viewer>

  </div>
</template>

<script>
import { uploadImg,querySignature,uploadOSSFile  } from '@/api/index'
import { fillUrl } from '@/utils'
import uuidv1 from "uuid/v1"
import { decrypt,encrypt,ossType } from '@/api/aesUtil'

/**
 *属性
 *@fileListArr默认值
 * [{
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    }]
 *
 *@limit 图片限制的个数
 *方法
 * gainList 获取图片列表
 * gainStatus 获取的图片是否在上传中
 */

export default {
  name: 'upmanyimgcomp',
  props: {
    filelistarr: {
      type: Array,
      default() {
        return []
      }
    },
    limit: {
      type: Number,
      default: 5
    },
    disabled: {
      type: Boolean,
      default: false
    },
    size: {
      type: Number,
      default: 2
    },
    filetype: {
      type: String,
      default: 'jpg,jpeg,png'
    },
    // 传B/KB/MB
    sizeunit: {
      type: String,
      default: 'MB'
    }
  },
  computed: {
    fileTypeArr() {
      const separator = this.filetype.match(/\W/)[0]
      return this.filetype.toLowerCase().split(separator)
    },
    acceptFileType() {
      return this.filetypeArr.join(',')
    }
  },
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      loading: false,
      fileList: this.filelistarr,
      // disabled1: this.disabled
      clent: null,
      options: {
        'inline': true, // 是否启用inline模式
 
        'button': true, // 是否显示右上角关闭按钮
 
        'navbar': true, // 是否显示缩略图底部导航栏
 
        'title': true, // 是否显示当前图片标题，默认显示alt属性内容和尺寸
 
        'toolbar': true, // 是否显示工具栏
 
        'tooltip': true, // 放大或缩小图片时，是否显示缩放百分比，默认true
 
        'fullscreen': true, // 播放时是否全屏，默认true
 
        'loading': true, // 加载图片时是否显示loading图标，默认true
 
        'loop': true, // 是否可以循环查看图片，默认true
 
        'movable': true, // 是否可以拖得图片，默认true
 
        'zoomable': true, // 是否可以缩放图片，默认true
 
        'rotatable': true, // 是否可以旋转图片，默认true
 
        'scalable': true, // 是否可以翻转图片，默认true
 
        'toggleOnDblclick': true, // 放大或缩小图片时，是否可以双击还原，默认true
 
        'transition': true, // 使用 CSS3 过度，默认true
 
        'keyboard': true, // 是否支持键盘，默认true
 
        'zoomRatio': 0.1, // 鼠标滚动时的缩放比例，默认0.1
 
        'minZoomRatio': 0.01, // 最小缩放比例，默认0.01
 
        'maxZoomRatio': 100, // 最大缩放比例，默认100
 
        'url': 'data-source', // 设置大图片的 url
 
         viewed(evt) {
          // 渲染完成，所有方法均可调用
          console.log('viewed', evt)
        }
      },
      images: []       

    }
  },
  methods: {
    inited(viewer) {
      // 初始化，可获取 viewer
      console.log('inited', viewer)
      this.$viewer = viewer
    },
    async handlePreview(file) {
      console.log('handlePreview',file.url)
      //this.previewImage = file.url || file.preview
      //this.previewVisible = true
      this.images = [file.url || file.preview]
      this.$viewer.show()

    },
    handleCancel() {
      this.previewVisible = false
    },
    async httpRequest(info) {
      const { file } = info

      try {
        let that = this

        const signRes = await querySignature("image")
        if (signRes.code === 0) {
            if(signRes.data.tyCloudFlag=='0'){
              const filename = file.name;
              const size = file.size;
              console.log("signRes",signRes,filename)
              const fileExt = filename.split(".");
              const uuid = uuidv1();
              let formData = new FormData();
              //注意formData里append添加的键的大小写
              formData.append('key', signRes.data.dir + uuid + "." + fileExt[1]); //存储在oss的文件路径
              formData.append('OSSAccessKeyId', signRes.data.accessid); //accessKeyId
              formData.append('policy', signRes.data.policy); //policy
              formData.append('Signature', signRes.data.signature); //签名
              //formData.append('callback', signRes.callback); //回调
              formData.append('success_action_status', 200); //成功后返回的操作码
              //如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
              formData.append("file", file);

              var res = await uploadOSSFile(signRes.data.host, formData);
              const imageUrl = signRes.data.host.replaceAll('http://','https://')+'/'+signRes.data.dir + uuid + "." + fileExt[1];
            // const { name, uid, size } =
              const obj =  { 'name':filename, 'uid':uuid, 'size':size }
              obj.url = imageUrl
              console.log(obj);
              this.fileList.push(obj)
              console.log(this.filelistarr)
              this.$emit('gainList', this.fileList)
              this.loading = false
              this.$message.success('上传成功')
            }
            else
            {
              
              const filename = file.name;
              const size = file.size;

              const fileExt = filename.split(".");
              const uuid = uuidv1();
              
              var params = {
                Body: file,
                Bucket: signRes.data.bucket,
                Key: signRes.data.dir + uuid + "." + fileExt[1]
              }
              that.client.putObject(params, function (err, data) {
                if (err) {
                  that.loading = false
                  that.$message.error('上传失败')
                } else {
  
                  const imageUrl = signRes.data.host+'/'+signRes.data.dir + uuid + "." + fileExt[1];
                  const obj =  { 'name':filename, 'uid':uuid, 'size':size }
                  obj.url = imageUrl

                  that.fileList.push(obj)

                  that.$emit('gainList', this.fileList)
                  that.loading = false
                  that.$message.success('上传成功')
                }
              })

            }
        }

      } catch (e) {
        console.info('error??', e)
        this.loading = false
        this.$message.error('上传失败')
      }
    },
    beforeUpload(file) {
      // 上传之前
      const suffix = file.name.match(/\.([^.]+)$/)[1].toLowerCase()
      const isTypeArr = this.fileTypeArr.some(item => item === suffix)
      if (!isTypeArr) {
        this.loading = false
        this.$message.error(`请上传${this.fileType}格式的图片!`)
      }
      let isLtSize
      if (this.sizeUnit === 'MB' || this.sizeUnit === undefined) {
        isLtSize = file.size / 1024 / 1024 < this.size
      } else if (this.sizeUnit === 'KB') {
        isLtSize = file.size / 1024 < this.size
      } else {
        isLtSize = file.size < this.size
      }

      if (!isLtSize) {
        this.loading = false
        this.$message.error(
          `图片大小不能超过${this.size}${
            this.sizeUnit === undefined ? 'MB' : this.sizeUnit
          }!`
        )
      }
      return isTypeArr && isLtSize
    },
    uploadImg(info) {
      this.loading = true
      if (info.file.status === 'removed') {
        this.loading = false
        this.fileList = info.fileList
        this.$emit('update:filelistarr', this.fileList)
        this.$emit('gainList', this.fileList)
      }
      if (info.file.status === 'done') {
        // console.log(1111)
      }
      if (!info.file.status) {
        this.loading = false
      }
    },
    initOss () {
      let that = this
      querySignature("init").then(res=>{
        if (res.code === 0 && res.data.tyCloudFlag=='1') {
          that.client = new ObsClient({
              access_key_id: res.data.accessid,       
              secret_access_key: decrypt(res.data.signature),  
              server : res.data.endPoint
          });
        }
      })
    }
  },
  mounted() {

      this.initOss()
  },
  watch: {
    loading(newValue) {
      this.$emit('gainStatus', newValue)
    },
    filelistarr: {
      handler(val) {
        this.fileList = val
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
.pic-wrap {
  .change-img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -5px;
    margin-left: -8px;
  }
  /deep/ .ant-upload-list-item {
    padding: 0;
  }
  img {
    width: 100px;
    height: 100px;
  }
  .up-bc {
    opacity: 0.5;
  }
}
.img-modal /deep/.ant-modal-mask{
    z-index: 1099;
}
.img-modal /deep/ .ant-modal-wrap {
  z-index: 1099;
}

</style>
